﻿using System;
using System.Xml;
using System.Xml.Linq;
using System.Text;

namespace Twi.COMMON.HTTP
{
    public static class StringExtensions
    {
        /// <summary>
        /// 获取当前菜单名称
        /// </summary>
        public static Func<string> GetMenuName;

        /// <summary>
        /// 获取IP
        /// </summary>
        public static Func<string> GetIP;


        private static string _menuName = "未知";

        public static string MenuName
        {
            get { return _menuName; }
            set { _menuName = value; }
        }
        /// <summary>
        /// 在产生xml文件的时候，过滤低位非打印字符
        /// </summary>
        /// <param name="tmp"></param>
        /// <returns></returns>
        private static string ReplaceLowOrderASCIICharacters(string tmp)
        {
            StringBuilder info = new StringBuilder();
            foreach (char cc in tmp)
            {
                int ss = (int)cc;
                if (((ss >= 0) && (ss <= 8)) || ((ss >= 11) && (ss <= 12)) || ((ss >= 14) && (ss <= 32)))
                    info.AppendFormat(" ", ss);
                else info.Append(cc);
            }
            return info.ToString();
        }

        private static void FilterXElement(XElement xe)
        {
            if (xe.HasElements)
            {
                foreach (XElement subXe in xe.Elements())
                {
                    if (subXe.HasElements)
                    {
                        FilterXElement(subXe);
                    }
                    else
                    {
                        string tempValue = ReplaceLowOrderASCIICharacters(subXe.Value);
                        subXe.SetValue(tempValue);
                    }
                }
            }
            else
            {
                string tempValue = ReplaceLowOrderASCIICharacters(xe.Value);
                xe.SetValue(tempValue);
            }
        }

        public static HttpResponseMessage HttpPost(this string uri, params object[] xeContents)
        {
            uri = Utils.GetAbsoluteUrl(uri);
            if (!uri.ToLower().Contains("http"))  //用于编码环境下调用验证
                return null;
            uri = InitUriParam(uri);
            XNamespace xn = "DataRootElement";
            XElement xeDataRoot = new XElement(xn + "DataRoot");
            if (xeContents != null)
            {
                foreach (object xe in xeContents)
                {
                    if (xe is XElement)
                    {
                        FilterXElement(xe as XElement);
                    }
                }
                xeDataRoot.Add(xeContents);
            }
            HttpClient client = new HttpClient();
            client.TransportSettings.ConnectionTimeout = new TimeSpan(2, 0, 0);
            HttpContent content = HttpContentExtensions.Create(xeDataRoot);
            HttpResponseMessage res = client.Post(uri, content);
            return res;
        }

        public static HttpResponseMessage HttpPost(this string uri, bool isFileServer = false, params object[] xeContents)
        {
            uri = isFileServer ? Utils.GetFileAbsoluteUrl(uri) : Utils.GetAbsoluteUrl(uri);
            if (!uri.ToLower().Contains("http"))  //用于编码环境下调用验证
                return null;
            uri = InitUriParam(uri);
            XNamespace xn = "DataRootElement";
            XElement xeDataRoot = new XElement(xn + "DataRoot");
            if (xeContents != null)
            {
                foreach (object xe in xeContents)
                {
                    if (xe is XElement)
                    {
                        FilterXElement(xe as XElement);
                    }
                }
                xeDataRoot.Add(xeContents);
            }

            HttpClient client = new HttpClient();
            client.TransportSettings.ConnectionTimeout = new TimeSpan(2, 0, 0);
            HttpContent content = HttpContentExtensions.Create(xeDataRoot);

            HttpResponseMessage res = client.Post(uri, content);
            return res;
        }



        public static HttpResponseMessage HttpPost(this string uri, byte[] buffer, bool isFileServer = false)
        {
            uri = isFileServer ? Utils.GetFileAbsoluteUrl(uri) : Utils.GetAbsoluteUrl(uri);
            if (!uri.ToLower().Contains("http"))  //用于编码环境下调用验证
                return null;
            //uri = InitUriParam(uri);
            HttpClient client = new HttpClient();
            client.TransportSettings.ConnectionTimeout = new TimeSpan(2, 0, 0);
            HttpContent content = HttpContent.Create(buffer);
            HttpResponseMessage res = client.Post(uri, content);
            return res;
        }

        public static HttpResponseMessage HttpPost(this string uri, HttpContent content, bool isFileServer = false)
        {
            uri = isFileServer ? Utils.GetFileAbsoluteUrl(uri) : Utils.GetAbsoluteUrl(uri);
            if (!uri.ToLower().Contains("http"))  //用于编码环境下调用验证
                return null;
            HttpClient client = new HttpClient();
            client.TransportSettings.ConnectionTimeout = new TimeSpan(2, 0, 0);
            HttpResponseMessage res = client.Post(uri, content);
            return res;
        }

        public static HttpResponseMessage HttpDelete(this string uri, bool isFileServer = false)
        {
            uri = isFileServer ? Utils.GetFileAbsoluteUrl(uri) : Utils.GetAbsoluteUrl(uri);
            if (!uri.ToLower().Contains("http"))  //用于编码环境下调用验证
                return null;
            uri = InitUriParam(uri);
            XElement xeDataRoot = new XElement("DataRoot");
            HttpClient client = new HttpClient();
            client.TransportSettings.ConnectionTimeout = new TimeSpan(2, 0, 0);
            HttpContent content = HttpContentExtensions.Create(xeDataRoot);
            HttpResponseMessage res = client.Delete(uri, content);
            return res;
        }

        public static HttpResponseMessage HttpGet(this string uri, bool isFileServer = false)
        {
            uri = isFileServer ? Utils.GetFileAbsoluteUrl(uri) : Utils.GetAbsoluteUrl(uri);
            if (!uri.ToLower().Contains("http"))  //用于编码环境下调用验证
                return null;
            uri = InitUriParam(uri);
            HttpClient client = new HttpClient();
            client.TransportSettings.ConnectionTimeout = new TimeSpan(2, 0, 0);
            HttpResponseMessage res = client.Get(uri);
            return res;
        }
        public static HttpResponseMessage HttpGet(this string uri, HttpQueryString queryString, bool isFileServer = false)
        {
            uri = isFileServer ? Utils.GetFileAbsoluteUrl(uri) : Utils.GetAbsoluteUrl(uri);
            if (!uri.ToLower().Contains("http"))  //用于编码环境下调用验证
                return null;
            uri = InitUriParam(uri);
            HttpClient client = new HttpClient();
            client.TransportSettings.ConnectionTimeout = new TimeSpan(2, 0, 0);
            HttpResponseMessage res = client.Get(new Uri(uri), queryString);
            return res;
        }

        private static string InitUriParam(string uri)
        {

            string menuName = MenuName;
            if (GetMenuName != null)
            {

                menuName = GetMenuName();
            }
            string ip = string.Empty;
            if (GetIP != null)
            {
                ip = GetIP();
            }
            else
            {
                ip = ConstClass.IP;
            }
            uri += string.Format("&IP={0}", ConstClass.IP);
            uri += string.Format("&MACAddress={0}", ConstClass.MACAddress);
            uri += string.Format("&MenuName={0}", menuName);
            uri += string.Format("&RequestKey={0}", Guid.NewGuid().ToString("N"));
            uri += string.Format("&OperateType={0}", 1);
            uri += string.Format("&OperateName={0}", ConstClass.OperateName);

            return uri;
        }

    }
}
